#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    :   difference.py
@Time    :   2021/12/03 18:11:22
@Author  :   glx 
@Version :   1.0
@Contact :   18095542g@connect.polyu.hk
@Desc    :   None
"""

# here put the import lib
from copy import deepcopy
import pandas as pd
from datetime import datetime, timedelta


def do_diff_test(smooth_data, ERROR_N=[3]):
    """do diff test with smooth data and ERROR_N default is 3
    input: smooth_data, ERROR_N
    output: diff_data, turbulence_point_index, upper_bound, lower_bound
    """

    diff_data = {}
    turbulence_point_index = {}
    lower_bound = {}
    upper_bound = {}
    turbulence_point_result = {}

    # 对每个目标做差分计算
    key = "Freq"
    diff_data[key] = smooth_data[key].diff().dropna()

    # print(key, ":",diff_data[key].max(), diff_data[key].min())
    upper = diff_data[key].mean() + diff_data[key].std() * ERROR_N
    lower = diff_data[key].mean() - diff_data[key].std() * ERROR_N

    lower_bound[key] = pd.Series(lower, index=diff_data[key].index)
    upper_bound[key] = pd.Series(upper, index=diff_data[key].index)

    if (upper - lower) <= 0.01:
        # 排除整体波动很小的数据
        turbulence_point_index[key] = (
            diff_data[key][(diff_data[key] < lower) & (diff_data[key] > upper)]
            .dropna()
            .index
        )

        # print(turbulence_point_index[key])
    # 提取出界的数据
    turbulence_point_index[key] = (
        diff_data[key][(diff_data[key] < lower) | (diff_data[key] > upper)]
        .dropna()
        .index
    )

    # 获取json 结果
    turbulence_point_result[key] = [
        (True, index) if index in turbulence_point_index[key] else (False, index)
        for index in smooth_data[key].index
    ]

    # turbulence_point_reindex = {}
    # for key in smooth_data["ts_range"].index:
    #     turbulence_point_reindex[key] = smooth_data["ts_range"].iloc[
    #         turbulence_point_index[key]
    #     ]

    print("diff test done".center(100, "="))
    return (
        diff_data,
        turbulence_point_result,
        turbulence_point_index,
        # turbulence_point_reindex,
        upper_bound,
        lower_bound,
    )


def merge_turb_point(indexes):
    """合并连续区间"""
    indexes.sort()  # 对索引进行排序
    merged = []  # 存储合并后的区间

    start = indexes[0]  # 初始化起始索引
    end = indexes[0]  # 初始化结束索引

    for i in range(1, len(indexes)):
        if indexes[i] == end + 1:  # 如果当前索引和上一个索引连续
            end = indexes[i]  # 更新结束索引
        else:
            if (
                start == end
            ):  # 如果起始索引和结束索引相同，则表示只有一个索引，不是连续的
                merged.append(start)
            else:  # 否则，将起始索引和结束索引合并为一个区间
                merged.append((start, end))
            start = indexes[i]  # 更新起始索引
            end = indexes[i]  # 更新结束索引

    # 处理最后一个区间或单个索引
    if start == end:
        merged.append(start)
    else:
        merged.append((start, end))

    return merged


if __name__ == "__main__":
    x = [
        1,
        3,
        4,
        5,
        6,
        8,
        10,
    ]
    print(merge_turb_point(x))
#     from get_matlab_data import get_data
#     from visualize import do_visualize, visualize_smooth
#     from smooth_data import do_smooth


#     output_data_folder = "data\out_put"
#     data:dict = get_data(output_data_folder)

#     # 平滑Freq曲线
#     smooth_data = do_smooth(data)
#     diff_data, turbulence_point_index, upper_bound, lower_bound = do_diff_test(smooth_data, 3)

# print(smooth_data["ship"].iloc[turbulence_point_index["ship"]])
